package com.xsd.awen.utils;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.List;

public class ExcelUtils {

    public static <T> List<T> toList(Sheet sheet,String[] properties,int startRow,Class<T> tClass){
        List<T> data = Lists.newArrayList();

        int lastRowNum = sheet.getLastRowNum();

        try {
            for( int i=startRow ; i<=lastRowNum ; i++ ){
                Row row = sheet.getRow(i);
                if( row != null ){
                    T t = newInstance(tClass);
                    for( int j=0 ; j<properties.length ; j++ ){
                        Object cellValue = getCellValue(row.getCell(j));
                        if( cellValue != null && cellValue.toString().trim().length()>0 ){
                            PropertyUtils.setProperty(t,properties[j],cellValue);
                        }
                    }
                    data.add(t);
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }

        return data;
    }

    private static Object getCellValue(Cell cell){
        if( cell == null ){
            return null;
        }
        if( cell.getCellType() == CellType.STRING ){
            return cell.getStringCellValue();
        }else if( cell.getCellType() == CellType.NUMERIC ){
            return BigDecimal.valueOf(cell.getNumericCellValue());
        }else if( cell.getCellType() == CellType.FORMULA ){
            return BigDecimal.valueOf(cell.getNumericCellValue());
        }else {
            return null;
        }

    }

    private static <T> T newInstance(Class<T> tClass){
        try {
            return tClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("");
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        //ExcelUtils.toList();
    }

}

